#include <REGX52.H>

//各个数据的命令
#define Second 		 0x80
#define Minute 		 0x82
#define Hour   		 0x84
#define Date   		 0x86
#define Month  		 0x88
#define Day    		 0x8a
#define Year   		 0x8c
#define WriteProtect 0x8e

arr_Time[7] = {0x57,0x59,0x23,0x14,0x10,0x01,0x24};

sbit  DS1302_IO   = P3^4;  
sbit  DS1302_CE   = P3^5;
sbit  DS1302_SCLK = P3^6;

void DS1302_Init()//初始化
{
		
	DS1302_CE = 0;
	DS1302_SCLK = 0;
	
}

void DS1302_Write(unsigned char Commend , Data)//写入命令和数据
{
	unsigned char i = 0;
	
	DS1302_CE = 1;
	
	for(i = 0 ; i < 8 ; i++ )
	{
		DS1302_IO = Commend & (0x01 << i);
		DS1302_SCLK = 0;
		DS1302_SCLK = 1;
		
	}
	
	for(i = 0 ; i < 8 ; i++ )
	{
		DS1302_IO = Data & (0x01 << i);
		DS1302_SCLK = 0;
		DS1302_SCLK = 1;
	
	}
	
	DS1302_SCLK = 0;
	DS1302_CE = 0;
	 
}

int DS1302_Read(unsigned char Commend)//读出时间
{
	unsigned char Data = 0;
	
	unsigned char i = 0;
	
	unsigned char decimal = 0;
	
	Commend |= 0x01;
	
	DS1302_CE = 1;
	
	for(i = 0 ; i < 8 ; i++ )
	{
		DS1302_IO = Commend & (0x01 << i);
		
	
		DS1302_SCLK = 0;
		DS1302_SCLK = 1;
	}
	
	for(i = 0 ; i < 8 ; i++ )
	{
	
		DS1302_SCLK = 1;
		DS1302_SCLK = 0;
		
		if(DS1302_IO)  { Data = Data | (0x01 << i); } 
	}
	
	DS1302_CE = 0;
	
	DS1302_IO = 0;
	
	decimal = (Data/16)*10 + Data%16;	
	
	return decimal;
	
}

void Set_Time(void)
{
	 DS1302_Write(Second,arr_Time[0]);
	 DS1302_Write(Minute,arr_Time[1]);
	 DS1302_Write(Hour,arr_Time[2]);
	 DS1302_Write(Date,arr_Time[3]);
	 DS1302_Write(Month,arr_Time[4]);
	 DS1302_Write(Year,arr_Time[6]);
}
void Start_Time(void)
{
	arr_Time[0] = DS1302_Read(Second);
	arr_Time[1] = DS1302_Read(Minute);
	arr_Time[2] = DS1302_Read(Hour);
	arr_Time[3] = DS1302_Read(Date);
	arr_Time[4] = DS1302_Read(Month);
	arr_Time[6] = DS1302_Read(Year);
}
































